package ihm.panel.file;

import ihm.applet.KrakenApplet;

import ihm.panel.PanelInterface;
import ihm.tool.AppletConstant;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import tools.PasswordSecurity;

import bdd.standalone.bean.User;

//import bdd.internal.bean.User;
//import bdd.internal.hibernate.HibernateUtil;

/**
 * Affiche le panneau de login.
 * @author Guillaume Pocas & Jean-Fraçois Augé
 */
public class LoginPanel extends JPanel implements ActionListener, PanelInterface {

	private static final long serialVersionUID = 1L;
	private JLabel connect_jl, login_jl, password_jl;
	private JTextField login_jtf, password_jtf;
	private JButton connect_jb;
	private KrakenApplet applet;

	/**
	 * Constructeur.
	 * @param app
	 */
	public LoginPanel(KrakenApplet app) {
		this.applet = app;
		this.initPanel();
		this.initActions();
	}

	@Override
	public void initPanel() {
		this.setLayout(new GridBagLayout());
		GridBagConstraints constraints = new GridBagConstraints();

		connect_jl = new JLabel("Veuillez vous connecter");

		login_jl = new JLabel("Login : ");

		password_jl = new JLabel("Mot de passe : ");

		login_jtf = new JTextField("admin");
		login_jtf.setPreferredSize(AppletConstant.FIELD_SIZE);

		password_jtf = new JPasswordField("admin");
		password_jtf.setPreferredSize(AppletConstant.FIELD_SIZE);

		connect_jb = new JButton("Connexion");
		connect_jb.setPreferredSize(AppletConstant.BUTTON_SIZE);

		constraints.insets = new Insets(AppletConstant.BUTTON_INSET,
				AppletConstant.BUTTON_INSET,
				AppletConstant.BUTTON_INSET,
				AppletConstant.BUTTON_INSET);

		constraints.gridx = 0;
		constraints.gridy = 0;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		constraints.anchor = GridBagConstraints.NORTH;
		constraints.fill = GridBagConstraints.NONE;
		add(connect_jl, constraints);

		constraints.gridx = 1;									// position en x
		constraints.gridy = 1;									// position en y
		constraints.gridwidth = GridBagConstraints.REMAINDER;	// largeur de l'object en nombre de case, ici le reste de la ligne
		constraints.anchor = GridBagConstraints.EAST;			// l'ancrage de l'object
		constraints.fill = GridBagConstraints.NONE;				// est ce que l'object prend toute la case?
		add(login_jtf, constraints);

		constraints.gridx = 1;
		constraints.gridy = 2;
		constraints.gridwidth = 1;
		constraints.anchor = GridBagConstraints.EAST;
		constraints.fill = GridBagConstraints.NONE;
		add(password_jtf, constraints);

		constraints.gridx = 0;
		constraints.gridy = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		constraints.anchor = GridBagConstraints.WEST;
		constraints.fill = GridBagConstraints.HORIZONTAL;
		add(login_jl, constraints);

		constraints.gridx = 0;
		constraints.gridy = 2;
		constraints.gridwidth = 1;
		constraints.anchor = GridBagConstraints.WEST;
		constraints.fill = GridBagConstraints.HORIZONTAL;
		add(password_jl, constraints);

		constraints.gridx = 0;
		constraints.gridy = 3;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		constraints.anchor = GridBagConstraints.SOUTH;
		constraints.fill = GridBagConstraints.NONE;
		add(connect_jb, constraints);
	}

	/**
	 * Initialise les actions.
	 */
	public void initActions() {
		connect_jb.addActionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource().equals(connect_jb)) {

			// debug
			/*Session session = applet.getSession();
			Transaction tx = session.beginTransaction();
			User user = new User("test", "test", "mail", Rank.Administrateur, Civility.Madame);
			session.save(user);
			user.setUser_pwd(PasswordSecurity.sha256(user.getUser_pwd_default(),""));
			session.save(user);
			tx.commit();
			System.out.println("adding a new user "+session);
			session.flush();*/

			System.out.println("mot de passe en clair "+password_jtf.getText());
			System.out.println("mot de passe en chiffré "+PasswordSecurity.sha256(password_jtf.getText(),""));

			//verif remplissage des champs
			if(this.login_jtf.getText().isEmpty() || this.password_jtf.getText().isEmpty()) {
				//lancer un pop up d'erreur
				JOptionPane.showMessageDialog(this,
						"Veuillez remplir les champs Login et Mot de passe !", 
						"Champs non remplis", 
						JOptionPane.INFORMATION_MESSAGE );
			}
			else{				
				Session session = applet.getSession();
				@SuppressWarnings("unchecked")
				List<User> resultats = session.createCriteria(User.class).add(Restrictions.eq("user_mail", login_jtf.getText())).list();

				if(resultats.size() == 0) {
					JOptionPane.showMessageDialog(this,
							"Les identifiants ne sont pas reconnus : vérifier les informations saisies.",
							"Erreur de login",
							JOptionPane.ERROR_MESSAGE);
				}
				else{
					//System.out.println("size : "+resultats.size());
					for(int i = 0; i < resultats.size(); i++) {
						//Debug
						//System.out.println(resultats.get(i));
						byte[] password = PasswordSecurity.sha256(password_jtf.getText(),resultats.get(i).getUser_seedPwd());
						if(Arrays.equals(resultats.get(i).getUser_pwd(),password)) {
							//premiere connexion
							if(resultats.get(i).getUser_firstcon() == true){
								
								//applet.setUser(resultats.get(i));
								applet.setUser_ID(resultats.get(i).getUser_id());
								
								new ChangePassword(this.applet);
								applet.setPanel("Login");
								this.login_jtf.setText("");
								this.password_jtf.setText("");
							}
							else{
								//applet.setUser(resultats.get(i));
								//applet.setUserLogged(true);
								//((KrakenMenuBar) applet.getJMenuBar()).setMenuPermissions(true); 
								// TODO remplacer cette methode
								//applet.getHeaderMenu().administrationMenu();
								//applet.initTabs(applet.getUser().getUser_rank());
								this.login_jtf.setText("");
								this.password_jtf.setText("");
								//applet.connect(resultats.get(i));
								applet.connect(resultats.get(i).getUser_id());
								//applet.setPanel("Accueil");
							}
						}
						else{
							System.out.println("Mauvais mdp pour " + login_jtf.getText() + " : "+password);
							JOptionPane.showMessageDialog(this, 
									"Le mot de passe saisi pour cet identifiant n'est pas valide.", 
									"Erreur de login", 
									JOptionPane.ERROR_MESSAGE );
							//System.out.println(resultats.get(i).getUser_mail()+" "+login_jtf.getText());
							System.out.println("Stocké : "+resultats.get(i).getUser_pwd().toString()+"\nEntré : "+password.toString());
						}
						//Debug
						//System.out.println(resultats.get(i).getUser_mail()+" "+login_jtf.getText());
						//System.out.println(resultats.get(i).getUser_pwd()+" "+password_jtf.getText());
					}
					session.close();
				}
			}
		}
	}

}
